<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Login extends MY_Controller {

    private $data;

    function __construct() {
        parent::__construct();
        $this->session->set_userdata(array('Url' => uri_string()));
        if ($this->logged_in()) {
            redirect(base_url('home'), 'refresh');
        }
        $this->load->library("form_validation");
        $this->load->helper('phpmailer');
        $this->load->model('member_model', '', TRUE);
        $this->lang->load('mailsubject');
		$this->load->library('securimage');
		$this->load->library('securimage');
    }

    function index() {

        //This method will have the credentials validation
        $this->load->library('form_validation');
        $this->load->helper('registration');
        $this->load->helper(array('form'));
        $type = $this->input->post('type');
        $this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean');
        $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');

        if (!empty($_POST) && $this->form_validation->run() == TRUE) {
            if ($type == 'popup') {
                redirect(base_url("home"), 'refresh');
            }
            $json = array();
            $json['status'] = true;
            $redirect = $this->session->userdata("redirect", 'refresh');
            if (!empty($redirect)) {
                $json['redirect'] = $redirect;
            } else {
                $json['redirect'] = base_url("home", 'refresh');
            }

            echo json_encode($json);
            exit();
        } else if (!empty($_POST)) {

            if ($type == 'popup') {
                redirect(base_url("login"), 'refresh');
            }
            $json = array();
            $json['status'] = false;
            $json['message'] = validation_errors();
            echo json_encode($json);
            exit();
        }
        $this->data['city'] = buildCityDropdown('city', 79);
        $this->data['state'] = buildStateDropdown('state', '', 79);
        $this->data['ward'] = buildWardDropdown('ward');
        $this->_templates['page'] = 'login/index';

        $this->site_lib->load($this->_templates['page'], $this->data);
    }

    function facebook_login() {

        $user = $this->facebook->getUser();
        if ($user) {
            try {
                $user_profile = $this->facebook->api('/me');
                if (!empty($user_profile)) {
                    $data = $this->_getData(array(
                        'fullname' => $user_profile['name'],
                        'email' => $user_profile['email'],
                        )
                    );
                    $infoUser = $this->member_model->check_email($data['lb_email']);
                    if (!$infoUser) {
                        $rs = $this->member_model->save_member(0, $data);
                    } else {
                        $this->member_model->save_member($infoUser['member_id'], $data);
                    }

                    $sess_array = array();
                    $sess_array = array(
                        'id' => $infoUser['member_id'],
                        'lb_email' => $user_profile['email'],
                        'lb_full_name' => $user_profile['name'],
                    );
                    $this->session->set_userdata('logged_in', $sess_array);
                }
                redirect("/", "refesh");
            } catch (FacebookApiException $e) {
                error_log($e);
                echo $e->getMessage();
                $user = null;
                exit();
            }
        }
        exit();
    }

    function register() {
        $this->load->library('form_validation');
        $this->load->helper('registration');
        $this->load->helper(array('form'));
        $this->form_validation->set_rules('email', 'Email', 'required|xss_clean');
        $this->form_validation->set_rules('fullname', 'Tên', 'required|xss_clean');
        $this->form_validation->set_rules('mobile', 'Điện thoại', 'required|xss_clean');
        $this->form_validation->set_rules('email', 'Email', 'required|xss_clean');
        $this->form_validation->set_rules('password', 'Mật khẩu', 'required|matches[repassword]');
        $this->form_validation->set_rules('repassword', 'Xác nhận mật khẩu', 'required');
        $json = array();
        $result = array();
		if($this->securimage->check($this->input->post('code'))){
      		 if ($this->form_validation->run() == true) {
            $data = $this->_getData($_POST);
            if ($this->member_model->check_email($data['lb_email']) == false) {
                $rs = $this->member_model->save_member(0, $data);
                $result = $this->member_model->checkMemberLogin($data['lb_email'], $_POST['password']);
                if ($result) {
                    $sess_array = array();
                    $sess_array = array(
                        'id' => $result['member_id'],
                        'lb_email' => $result['lb_email'],
                        'lb_full_name' => $result['lb_full_name']
                    );
                    $this->session->set_userdata('logged_in', $sess_array);
                    $json['status'] = true;

                    $redirect = $this->session->userdata("redirect");
                    if (!empty($redirect)) {
                        $json['redirect'] = $redirect;
                    } else {
                        $json['redirect'] = base_url("home");
                    }
                    //query the database

                    $subject = "Xác nhận đăng ký thông tin mua hàng";
                    $data_mail['user_name'] = $this->input->post('fullname');
                    $data_mail['contact_mail'] = $this->config->item('contact_email');
                    $data_mail['admin_email'] = $this->config->item('admin_email');
                    $data_mail['site_name'] = $this->config->item('site_name');
                    $data_mail['site_url'] = $this->config->item('base_url');
                    $email = $this->input->post('email');
                    $data_mail['confirm_url'] = base_url() . 'member/activeuser/' . $result['member_id'] . '/' . md5($email);
                    $message = $this->load->view('emails/vn/user_active_email', $data_mail, true);
                    $rs_email = send_email("no-reply@ngoinhabeyeu.com", $email, "no-reply@ngoinhabeyeu.com", $subject, $message);
                    //$rs_email= send_email($this->config->item('admin_email'),$email,$this->config->item('contact_email'), $subject, $message);
                    $json['status'] = true;
                    $json['message'] = 'Tài khoản của bạn đã tạo thành công.';
                }
            } else {
                $json['status'] = false;
                $json['message'] = 'Email này đã được sử dụng. Vui lòng chọn một email khác để tạo tài khoản.';
                $data['message_error'] = 'Vui lòng chọn một email khác để tạo tài khoản.';
                $this->data['city'] = buildCityDropdown('city', 79);
                $this->data['state'] = buildStateDropdown('state', '', 79);
                $this->data['ward'] = buildWardDropdown('ward');
                $this->_templates['page'] = 'login/index';
            }
        } else {

            $json['status'] = false;
            $json['errors'] = validation_errors();
            $json['message'] = 'Có lỗi sảy ra vui lòng kiểm tra lại.';
        }
		}else{
			$json['status'] = false;
            $json['message'] = 'Mã xác nhận sai. Vui lòng nhập lại.';
		}
        echo json_encode($json);
        exit();
    }

    function forgot_pass() {
        $this->form_validation->set_rules('email', 'Email', 'required|xss_clean');
        $this->form_validation->set_rules('email_confirm', 'Xác nhận email', 'required');
        $json = array();
        if ($this->form_validation->run() == true) {
            $email = $this->input->post('email');
            $rs = $this->member_model->check_email($email);
            if (!empty($rs)) {
                $newpass = substr(uniqid(md5(time())), 0, 6);
                $data['lb_password'] = $newpass;
                $data_pass = array('lb_password' => md5($newpass));

                //query the database
                $result = $this->member_model->save_member($rs['member_id'], $data_pass);

                if ($result) {
                    $json['redirect'] = base_url("home");
                    $subject = "Thông tin đổi mật khẩu";
                    $data_mail['user_name'] = $this->input->post('fullname');
                    $data_mail['contact_mail'] = $this->config->item('contact_email');
                    $data_mail['admin_email'] = $this->config->item('admin_email');
                    $data_mail['site_name'] = $this->config->item('site_name');
                    $data_mail['site_url'] = $this->config->item('base_url');
                    $data_mail['lb_password'] = $newpass;
                    $email = $this->input->post('email');
                    $data_mail['confirm_url'] = base_url() . 'member/activeuser/' . $result['member_id'] . '/' . md5($email);
                    $message = $this->load->view('emails/vn/user_forgot_pass_email', $data_mail, true);
                    $rs_email = send_email("no-reply@ngoinhabeyeu.com", $email, "no-reply@ngoinhabeyeu.com", $subject, $message);
                    //$rs_email= send_email($this->config->item('admin_email'),$email,$this->config->item('contact_email'), $subject, $message);

                    $json['message'] = 'Mật khẩu đã được tạo thành công. Vui lòng check mail để nhận mật khẩu mới.';
                } else {
                    $json['status'] = false;
                    $json['message'] = 'có lỗi sảy ra khi đổi mật khẩu. Xin vui lòng thử lại.';
                }
            } else {

                $json['status'] = false;
                $json['errors'] = validation_errors();
                $json['message'] = 'Tài khoản của bạn đã tồn tại trong hệ thống.';
            }
            echo json_encode($json);
            exit();
        }
    }

    function activeuser($member_id, $hash) {
        $data = array();
        $member = $this->member_model->get_member($member_id);
        if ($member) {
            if ($hash != '' && ($hash == md5($member['lb_email'])) && $member['bl_active'] == 1) {
                $data['str_mess'] = lang('reg.account_activated');
            } else if ($hash != '' && ($hash == md5($member['lb_email']))) {
                $this->member->save_member($member_id, array('bl_active' => 1));
                $data['str_mess'] = lang('reg.activated_successful');
            } else {
                $data['str_mess'] = lang('reg.activate_mistake') . '&nbsp;:&nbsp;<a href="mailto:' . $this->config->item('contact_email') . '">' . $this->config->item('contact_email') . '</>';
            }
        } else {
            $data['str_mess'] = lang('reg.member_not_exist');
        }
        $this->_templates['page'] = 'login/active_user';
        $this->site_lib->load($this->_templates['page'], $data);
    }

    private function _getData($data) {

        $reData = array();
        $reData['lb_email'] = !empty($data['email']) ? $data['email'] : "";
        $reData['lb_full_name'] = !empty($data['fullname']) ? $data['fullname'] : "";
        $reData['lb_phone'] = !empty($data['mobile']) ? $data['mobile'] : "";
        $reData['lb_address'] = !empty($data['address']) ? $data['address'] : "";
        $reData['lb_city'] = !empty($data['city']) ? $data['city'] : "";
        $reData['lb_state'] = !empty($data['state']) ? $data['state'] : "";
        $reData['lb_ward'] = !empty($data['ward']) ? $data['ward'] : "";
        $reData['lb_password'] = !empty($data['password']) ? md5($data['password']) : "";
        $reData['dt_create'] = date('Y-m-d H:i:s');
        $reData['bl_active'] = 1;

        return $reData;
    }

    function check_database($password) {
        //Field validation succeeded.  Validate against database
        $username = $this->input->post('email');

        //query the database
        $result = $this->member_model->checkMemberLogin($username, $password);
        $json = array();
        if ($result) {

            $sess_array = array();
            $sess_array = array(
                'id' => $result['member_id'],
                'lb_email' => $result['lb_email'],
                'lb_full_name' => $result['lb_full_name']
            );

            $this->session->set_userdata('logged_in', $sess_array);

            return true;
        }
        $this->form_validation->set_message("check_database", "Nhập sai thông tin email hoặc mật khẩu!");

        return false;
    }

    public function fogot() {
        
    }

}